import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hitutor/Util/DateUtil.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/Check.dart';
import 'package:hitutor/Widget/ChooserBox.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyPage.dart';

import 'DistributingClass.dart';

class MyOrderList extends StatefulWidget {
  MyOrderList({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return MyOrderListState();
  }
}

class MyOrderListState extends State<MyOrderList> {
  List<dynamic> orders = [];

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getOrderData();
    });
    super.initState();
  }

  getOrderData() {
    HttpGo(context).get("/Lesson/GetPurchaseOrderList?studentId=${Global.studentId}", {}, (data) {
      orders = data["purchaseOrderList"];
      setState(() {});
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    return MyPage(
        "我的訂單",
        Container(
          color: MyColor.F8,
          child: RefreshIndicator(
              child: ListView.builder(
                  itemCount: orders.length,
                  itemBuilder: (BuildContext context, int index) {
                    return ItemOrder(orders[index]);
                  }),
              onRefresh: () async {
                getOrderData();
                return Future.value(true);
              }),
        ),
        rightWidgets: [
          TextBtn("付費延期", style: TextStyle(color: MyColor.BlueTxt), onTap: () {
            showWidgetDialog(context, DelayPay());
          }),
          Container(width: 12)
        ]);
  }
}

class ItemOrder extends StatefulWidget {
  dynamic order;

  ItemOrder(this.order);

  @override
  State<StatefulWidget> createState() {
    return _ItemOrder();
  }
}

class _ItemOrder extends State<ItemOrder> {
  lessonDelayClick() {
    HttpGo(context).post("/Lesson/GetClassExtensionContext", {
      "studentId": Global.studentId,
      "purchaseOrderId": widget.order["lessonOrderId"],
    }, (data) {
      showWidgetDialog(
          context,
          DelayClass(data["context"], onConfirm: () {
            confirmDelay();
          }));
    }, (code, error) => showToast(error));
  }

  confirmDelay() {
    HttpGo(context).post("/Lesson/ExtendClass", {
      "studentId": Global.studentId,
      "purchaseOrderId": widget.order["lessonOrderId"],
    }, (data) {
      showToast("課程延期成功");
      Global.myOrderKey.currentState?.getOrderData();
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    DateTime? startDate = getTimeByUtc(widget.order["lessonStartDate"]);
    DateTime? endDate = getTimeByUtc(widget.order["lessonEndDate"]);
    String startDateS = getStrTime(startDate, DateUtil.YMD);
    String endDateS = getStrTime(endDate, DateUtil.YMD);
    List<dynamic> subOrders = widget.order["subPurchaseOrderList"] ?? [];
    return Container(
        color: MyColor.White,
        padding: EdgeInsets.all(12),
        margin: EdgeInsets.only(top: 8),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text("${widget.order["lessonOrderId"]} 丨 ${widget.order["lessonName"]}",
              style: TextStyle(color: MyColor.BlueTxt, fontWeight: FontWeight.bold)),
          Container(
              padding: EdgeInsets.fromLTRB(0, 8, 0, 8),
              child: Row(children: [
                Text("$startDateS ~ $endDateS ", style: TextStyle(color: MyColor.Orange)),
                Visibility(
                    visible: widget.order["canExtendClass"],
                    child: Button("課程延期", height: 20, radius: 10, bgColor: MyColor.Orange, width: 80, onTap: lessonDelayClick))
              ])),
          ListView.separated(
            itemCount: subOrders.length,
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemBuilder: (BuildContext context, int index) {
              return ItemClass1(subOrders[index]);
            },
            separatorBuilder: (BuildContext context, int index) {
              return Container(height: 1, color: MyColor.EE, margin: EdgeInsets.symmetric(horizontal: 8));
            },
          )
        ]));
  }
}

///第一層
class ItemClass1 extends StatefulWidget {
  dynamic order;

  ItemClass1(this.order);

  @override
  State<StatefulWidget> createState() {
    return _ItemClass1();
  }
}

class _ItemClass1 extends State<ItemClass1> {
  bool open = false;

  @override
  Widget build(BuildContext context) {
    List<dynamic> subOrders = widget.order["subPurchaseOrderList"] ?? [];

    return Column(children: [
      GestureDetector(
          onTap: () {
            if (subOrders.length > 0) {
              open = !open;
              setState(() {});
            }
          },
          child: Container(
              padding: EdgeInsets.symmetric(vertical: 4),
              child: Row(children: [
                Opacity(
                  opacity: subOrders.length > 0 ? 1 : 0.5,
                  child: RotatedBox(quarterTurns: open ? 1 : 0, child: LocalImage("right_tra.png", width: 12, padding: EdgeInsets.all(6))),
                ),
                // Text("生活英文(中師50分) 100堂", style: TextStyle(color: MyColor.C7D)),
                Container(
                  constraints: BoxConstraints(maxWidth: 220),
                  child: Text("${widget.order["lessonName"]} 【${widget.order["changeRecords"]}堂】", style: TextStyle(color: MyColor.C7D)),
                ),
                Visibility(
                    visible: widget.order["forSplit"] == 1,
                    child: LocalImage("edit_2.png", width: 20, padding: EdgeInsets.all(6), onTap: () {
                      PageUtil().open(
                          context,
                          DistributingClass(
                            purchaseOrderId: widget.order["lessonOrderId"],
                            unitPrize: widget.order["unitPrize"],
                            changeRecords: widget.order["changeRecords"],
                            oldLessonName: widget.order["lessonName"],
                          ));
                    }))
              ]))),
      Visibility(
          visible: open,
          child: ListView.separated(
            itemCount: subOrders.length,
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemBuilder: (BuildContext context, int index) {
              return Padding(padding: EdgeInsets.only(left: 8), child: ItemClass1(subOrders[index]));
            },
            separatorBuilder: (BuildContext context, int index) {
              return Container(height: 1, color: MyColor.EE, margin: EdgeInsets.symmetric(horizontal: 8));
            },
          ))
    ]);
  }
}

///dialog
class DelayClass extends StatelessWidget {
  String content1 = "";
  Function() onConfirm;
  String content2 = "相關課程：\n(注意！所有相關課程將同步異動使用課程延期次數！)";

  DelayClass(this.content1, {required this.onConfirm});

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: Global.getWhiteBg(4),
        padding: EdgeInsets.all(14),
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          Text("課程延期", style: TextStyle(fontSize: 20, color: MyColor.BlueTxt, fontWeight: FontWeight.bold)),
          Container(height: 1, color: MyColor.BlueTxt, margin: EdgeInsets.fromLTRB(0, 12, 0, 12)),
          Text(content1),
          Text(content2, style: TextStyle(color: MyColor.Red)),
          Container(
              margin: EdgeInsets.fromLTRB(0, 16, 0, 8),
              child: Row(children: [
                Expanded(
                    child: TextBtn("取消", height: 32, style: TextStyle(color: MyColor.BlueTxt), onTap: () {
                  PageUtil().back(context);
                })),
                Expanded(
                    child: Button("送出", bgColor: MyColor.BlueTxt, height: 32, onTap: () {
                  onConfirm.call();
                  PageUtil().back(context);
                }))
              ]))
        ]));
  }
}

class DelayPay extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _DelayPay();
  }
}

class _DelayPay extends State<DelayPay> {
  int extendMonths = 1;
  dynamic totalPrice = 0;
  bool agree = false;

  choosePayType() {
    showWheelDialog(context, "", ["1個月", "2個月", "3個月", "4個月", "5個月", "6個月"], (i) {
      extendMonths = (i + 1);
      setState(() {});
      getAmount();
    });
  }

  getAmount() {
    HttpGo(context).get("/Lesson/GetExtendMonthsPrice?extendMonths=$extendMonths", {}, (data) {
      totalPrice = data["price"];
      setState(() {});
    }, (code, error) => showToast(error));
  }

  confirmClick() {
    HttpGo(context).get("/Member/GetExtendPaidUrl?studentId=${Global.studentId}&extendMonths=$extendMonths&payWay=2", {}, (data) {
      PageUtil().launchURL(data["paidUrl"]);
      PageUtil().back(context);
    }, (code, error) => showToast(error));
  }

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getAmount();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: Global.getWhiteBg(4),
        padding: EdgeInsets.all(14),
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          Text("付費延期", style: TextStyle(fontSize: 20, color: MyColor.BlueTxt, fontWeight: FontWeight.bold)),
          Container(height: 1, color: MyColor.BlueTxt, margin: EdgeInsets.fromLTRB(0, 12, 0, 12)),
          Row(children: [Text("延期月份："), Container(width: 100, child: ChooserBox("$extendMonths個月", onTap: choosePayType))]),
          Container(width: double.infinity, padding: EdgeInsets.fromLTRB(0, 8, 0, 8), child: Text("付費金額 $totalPrice 元")),
          // Row(children: [
          //   GestureDetector(
          //       onTap: () {
          //         agree = !agree;
          //         setState(() {});
          //       },
          //       child: Check(agree)),
          //   Text(" 勾選發送簡訊刷卡")
          // ]),
          Container(height: 8),
          Row(children: [
            LocalImage("warning.png", width: 16, padding: EdgeInsets.only(right: 8)),
            Text("僅限課程期限內得以付費延期", style: TextStyle(color: Color(0xffff3838), fontWeight: FontWeight.bold)),
          ]),
          Container(
              margin: EdgeInsets.fromLTRB(0, 16, 0, 8),
              child: Row(children: [
                Expanded(
                    child: TextBtn("取消", height: 32, style: TextStyle(color: MyColor.BlueTxt), onTap: () {
                  PageUtil().back(context);
                })),
                Expanded(child: Button("送出", bgColor: MyColor.BlueTxt, height: 32, onTap: confirmClick))
              ]))
        ]));
  }
}

// ///中間層
// class ItemClass2 extends StatefulWidget {
//   @override
//   State<StatefulWidget> createState() {
//     return _ItemClass2();
//   }
// }
//
// class _ItemClass2 extends State<ItemClass2> {
//   bool open = false;
//
//   @override
//   Widget build(BuildContext context) {
//     return Column(children: [
//       GestureDetector(
//           onTap: () {
//             open = !open;
//             setState(() {});
//           },
//           child: Container(
//               height: 32,
//               child: Row(children: [
//                 Container(width: 24),
//                 RotatedBox(quarterTurns: open ? 1 : 0, child: LocalImage("right_tra.png", width: 12, padding: EdgeInsets.all(6))),
//                 Text("生活英文(中師50分) 100堂", style: TextStyle(color: MyColor.C7D))
//               ]))),
//       Visibility(
//           visible: open,
//           child: ListView.builder(
//               itemCount: 3,
//               shrinkWrap: true,
//               padding: EdgeInsets.only(left: 24),
//               physics: NeverScrollableScrollPhysics(),
//               itemBuilder: (BuildContext context, int index) {
//                 return ItemClass2();
//               }))
//     ]);
//   }
// }
//
// ///底層
// class ItemClass3 extends StatelessWidget {
//   @override
//   Widget build(BuildContext context) {
//     return Container(
//         height: 32,
//         child: Row(
//           children: [Container(width: 96), Text("生活英文(中師50分) 100堂", style: TextStyle(color: MyColor.C7D))],
//         ));
//   }
// }
